package site.psvm.MyJpa.dao;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import site.psvm.MyJpa.annotation.TableName;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class BaseDao<T> {

    private static BasicDataSource dataSource;

    static {
        dataSource = new BasicDataSource();
        try {
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3307/ting?useSSL=false");
            dataSource.setUsername("root");
            dataSource.setPassword("password");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Class<T> beanClass;
    private static JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    public BaseDao() {
        //获得泛型父类的class类型参数变量,如果没有指定类型参数变量,则会出现类型转换异常
        beanClass = (Class<T>) ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public int add(T bean){
        Field[] fields = beanClass.getDeclaredFields();
        StringBuilder sql = new StringBuilder();
        sql.append("insert into ");
        sql.append(beanClass.getAnnotation(TableName.class).value());
        sql.append(" values (");
        for (int i = 0; i < fields.length; i++) {
            sql.append("?");
            if (i!=fields.length-1){
                sql.append(",");
            }
        }
        sql.append(")");

        //所有字段的值
        List<Object> paramList = new ArrayList<>();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object o = field.get(bean);
                paramList.add(o);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        int size = paramList.size();
        Object[] valuse = paramList.toArray(new Object[size]);
        System.out.println("sql模板: "+sql.toString());
        System.out.println("values: "+ Arrays.toString(valuse));
        return jdbcTemplate.update(sql.toString(), valuse);
    }
}
